package cn.com.guage.flink.wordcount;

import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.java.DataSet;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.DataSource;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

public class WordCountFormText {
	public static void main(String[] args) throws Exception {
        //创建执行环境
        ExecutionEnvironment env = ExecutionEnvironment.getExecutionEnvironment();

        //从文件读取数据
        String inputPath = "D:\\data\\test.log";
    
        DataSource<String> inputDataSet = env.readTextFile(inputPath);
       
        //数据集进行处理
        DataSet<Tuple2<String,Integer>> resultSet = inputDataSet.flatMap(new MyFlatMapper())
        .groupBy(0) //按照二元组第一个word分组
        .sum(1);      //按照二元组第二个数字求和

        resultSet.print();
    }

    //自定义类，实现FlatMapFunction接口
    public static class MyFlatMapper implements FlatMapFunction<String, Tuple2<String,Integer>>{

        /**
		 * 
		 */
		private static final long serialVersionUID = -6332218868988874763L;

		public void flatMap(String s, Collector<Tuple2<String, Integer>> collector){
            //按空格分词
            String[] words = s.split(" ");
            //遍历所有word 加工成二元组
            for(String word:words){
                collector.collect(new Tuple2<String,Integer>(word,1));
            }
        }
    }
}
